package com.xcc.server.decoder;

import com.alibaba.fastjson.JSON;
import com.xcc.server.domains.vo.Message;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;

import java.nio.charset.Charset;
import java.util.List;

/**
 * @Author: xcc
 * @Date: 2021/2/4 14:11
 * @Description: 服务端解码
 * 对接收到的数据进行解码
 */
public class MessageDecoder extends MessageToMessageDecoder<ByteBuf> {

    private final Charset charset;

    public MessageDecoder() {
        this(Charset.defaultCharset());
    }

    public MessageDecoder(Charset charset) {
        if (charset == null) {
            throw new NullPointerException("charset");
        } else {
            this.charset = charset;
        }
    }

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        String s = byteBuf.toString(this.charset);
        Message<String> message = JSON.parseObject(s, Message.class);
        list.add(message);  // list 不为空,会调用 ChatServerHandler
    }
}
